<template>
  <div class="custom-page">
    <a-form :form="formState" :labelAlign="`left`" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
      <!-- 基本信息 -->
      <div>
        <div class="descriptions-title">基本信息</div>
        <div>
          <a-row>
            <a-col :span="12">
              <a-form-item label="客户" name="company"> {{ info.companyTo }} </a-form-item>
            </a-col>
            <!-- <a-col :span="12">
              <a-form-item label="有效期" name="termof"> 2023-09-31 </a-form-item>
            </a-col> -->
            <a-col :span="12">
              <a-form-item label="订单类型" name="company">
                <!-- <a-radio-group v-model="formState.type" name="radioGroup" :default-value="1">
                  <a-radio :value="1"> 销售订单 </a-radio>
                  <a-radio :value="2"> 调拨订单 </a-radio>
                </a-radio-group> -->
                {{ info.orderType * 1 === 1 ? '销售' : '调拨' }}
              </a-form-item>
            </a-col>
            <!-- <a-col :span="12">
              <a-form-item label="来源订单号" name="termof">
                <a-input v-model="formState.termof" placeholder="请输入" />
                XXXXXXXXXXXXXXXXXXXX
              </a-form-item>
            </a-col> -->
            <!-- <a-col :span="12">
              <a-form-item label="外源订单号" name="termof">
                <a-input v-model="formState.termof" placeholder="请输入" />
                XXXXXXXXXXXXXXXXXXXXXX
              </a-form-item>
            </a-col> -->
          </a-row>
        </div>
      </div>
      <!-- 规格信息 -->
      <div>
        <div>
          <div class="title-wrap">
            <div class="title descriptions-title">规格信息</div>
            <div v-if="type == 0">
              <a-input-search
                ref="scanRef"
                v-model="udi"
                placeholder="输入条形码"
                size="large"
                @search="onScan"
                allowClear
                style="width: 500px"
              >
                <a-button slot="enterButton" icon="scan"> </a-button>
              </a-input-search>
              <a-button type="primary" style="margin-left: 20px" @click="stockUp()"> 备货 </a-button>
            </div>
          </div>
        </div>
        <div v-if="errInfo" class="err-info">{{ errInfo }}</div>
        <div style="margin-top: 30px">
          <a-collapse v-model="activeKey">
            <a-collapse-panel v-for="(l, i) in goodList" :key="i + 1 + ''">
              <template #header>
                <div class="good-header">
                  <span>规格名称：</span>
                  <span>{{ l.productName }} - {{ l.specName }} - {{ l.productCpbsbmtxmc }}</span>
                  <span style="margin-left: 30px">类型：</span>
                  <span>{{ l.productType * 1 == 0 ? '一物一码' : '一码多物' }}</span>
                  <span style="margin-left: 30px">数量：</span>
                  <span>{{ getStockUpNum(l) }}/{{ l.sum }}</span>
                  <div class="scan-info">
                    <!-- {{ getStockUpNum(l) }}/{{ l.sum }} -->
                    <a-icon v-if="l.source.length >= l.sum" type="check" style="color: green; margin-left: 20px" />
                    <a-popconfirm
                      title="是否确认提交核对结果?"
                      ok-text="确定"
                      cancel-text="取消"
                      @confirm="check(l, i)"
                    >
                      <a-button type="primary" v-if="isShowCheckBtn(l)" @click.stop style="margin-left: 20px">
                        核对提交
                      </a-button>
                    </a-popconfirm>
                  </div>
                </div>
              </template>
              <a-table
                :columns="l.productType * 1 == 0 ? columns : oneToManyColumns"
                size="small"
                :data-source="l.source"
                :pagination="false"
              >
                <a slot="action" slot-scope="text, records, index">
                  <a-popconfirm
                    title="是否确认删除该条数据?"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="delConfirm(records, i, index)"
                  >
                    <span v-if="!l.isChecked">删除</span>
                  </a-popconfirm>
                </a>
              </a-table>
            </a-collapse-panel>
          </a-collapse>
        </div>
      </div>
      <div class="button-wrap">
        <template v-if="[0, 1].indexOf(info.state * 1) > -1">
          <a-button @click="temporaryStorage()">保存</a-button>
          <a-button @click="submit()" type="primary" style="margin-left: 20px" :disabled="isSubmit"
            >保存并提交</a-button
          >
        </template>
        <a-button v-if="info.state * 1 == 2" @click="submit()" type="primary">审核通过</a-button>
        <a-button v-if="info.state * 1 == 3" @click="submit()" type="primary">出库完结</a-button>
      </div>
    </a-form>
    <modal-stock-up ref="stockUpRef"></modal-stock-up>
  </div>
</template>

<script>
import {
  outOrderInfo,
  outOrderTemporaryStorage,
  outOrderSubmitExamine,
  outOrderExaminePass,
  outOrderComplete,
  queryOutOrderStockUpList,
} from '@/api/order.js'
import { queryGoodByScanId, scanBindGood } from '@/api/good.js'
import ModalStockUp from './components/modal-stock-up.vue'
export default {
  data() {
    return {
      formState: {
        type: 1,
      },
      activeKey: undefined,
      goodList: [],
      stockUpList: [], // 备货列表
      info: {},
      udi: undefined,
      goodIndexObj: {},
      scanObj: {},
      type: 0, // 0:扫单;1:详情页面;
      errInfo: undefined,
    }
  },
  components: { ModalStockUp },
  mounted() {
    this.getInfo()
    this.inputFocus()
    const path = this.$route.path
    if (path.indexOf('info') > -1) {
      this.type = 1
    } else {
      this.type = 0
    }
  },
  computed: {
    columns() {
      const { type } = this
      const columns = [
        {
          title: '条形码',
          dataIndex: 'udi',
          key: 'udi',
          width: 200,
        },
        {
          title: '最小销售单元产品标识',
          dataIndex: 'productZxxsdycpbs',
          key: 'productZxxsdycpbs',
        },
        {
          title: '医疗器械唯一标识编码体系名称',
          dataIndex: 'productCpbsbmtxmc',
          key: 'productCpbsbmtxmc',
          width: 120,
        },
        {
          title: '最小销售单元中使用单元的数量',
          dataIndex: 'productZxxsydydsl',
          key: 'productZxxsydydsl',
          width: 120,
        },
        {
          title: '医疗器械注册人/备案人名称',
          dataIndex: 'productYlqxzcrbarmc',
          key: 'productYlqxzcrbarmc',
        },
        {
          title: '产品名称/通用名称',
          dataIndex: 'productName',
          key: 'productName',
        },
        {
          title: '型号规格/包装规格',
          dataIndex: 'productSpec',
          key: 'productSpec',
          width: 120,
        },
        {
          title: '库位',
          dataIndex: 'warePid',
          key: 'warePid',
          width: 100,
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ]
      if (type == 0) {
        return columns
      } else {
        return columns.slice(0, columns.length - 1)
      }
    },
    oneToManyColumns() {
      const { type } = this
      const columns = [
        // {
        //   title: '条形码',
        //   dataIndex: 'udi',
        //   key: 'udi',
        //   width: 200,
        // },
        {
          title: '最小销售单元产品标识',
          dataIndex: 'productZxxsdycpbs',
          key: 'productZxxsdycpbs',
        },
        {
          title: '医疗器械唯一标识编码体系名称',
          dataIndex: 'productCpbsbmtxmc',
          key: 'productCpbsbmtxmc',
          width: 120,
        },
        {
          title: '最小销售单元中使用单元的数量',
          dataIndex: 'productZxxsydydsl',
          key: 'productZxxsydydsl',
          width: 120,
        },
        {
          title: '医疗器械注册人/备案人名称',
          dataIndex: 'productYlqxzcrbarmc',
          key: 'productYlqxzcrbarmc',
        },
        {
          title: '产品名称/通用名称',
          dataIndex: 'productName',
          key: 'productName',
        },
        {
          title: '型号规格/包装规格',
          dataIndex: 'productSpec',
          key: 'productSpec',
          width: 140,
        },
        {
          title: '库位',
          dataIndex: 'warePid',
          key: 'warePid',
          width: 100,
        },
        {
          title: '数量',
          dataIndex: 'sums',
          key: 'sums',
          width: 80,
        },
        // {
        //   title: '操作',
        //   key: 'action',
        //   scopedSlots: { customRender: 'action' },
        // },
      ]
      return columns
      // if (type == 0) {

      // } else {
      //   return columns.slice(0, columns.length - 1)
      // }
    },
    isSubmit() {
      const { goodList } = this
      const row = goodList.filter((f) => f.isChecked)
      if (row && row.length === goodList.length) {
        return false
      } else {
        return true
      }
    },
  },
  methods: {
    inputFocus() {
      this.$refs.scanRef.$refs.input.focus()
    },
    delConfirm(e, i, index) {
      // console.log('delConfirm', e, i, index)
      this.scanObj[e.udi] = 0
      this.goodList[i].source.splice(index, 1)
      this.$set(this.goodList, i, { ...this.goodList[i] })
      // 自动对焦到输入框
      this.inputFocus()
    },
    stockUp() {
      const { stockUpList } = this
      this.$refs.stockUpRef.open({ dataSource: stockUpList })
    },
    // 是否展示核对按钮
    isShowCheckBtn(l) {
      if (l.productType * 1 === 0) {
        return l.source.length >= l.sum && !l.isChecked
      } else {
        return !l.isChecked
      }
    },
    // 获取当前备货数量
    getStockUpNum(e) {
      let num = e.source.length
      if (e.productType * 1 == 1 && num > 0) {
        num = 0
        e.source.forEach((c) => {
          num += c.sums
        })
      }
      return num
    },
    // 获取备货列表
    async getStockUpList() {
      try {
        const self = this
        const { goodList, info } = this
        const params = {
          orderId: info.id,
          wmsSpecInfo: goodList.map((e) => {
            return {
              productSpec: e.specName,
              productType: e.productType,
              sums: e.sum,
            }
          }),
        }
        const r = await queryOutOrderStockUpList(params)
        this.goodList.forEach((e, i) => {
          if (e.productType * 1 == 1) {
            const row = r.result.filter((f) => f.specName == e.specName)
            if (row && row.length > 0) {
              self.$set(self.goodList, i, {
                ...self.goodList[i],
                source: row[0].positionInfoList.map((c) => {
                  return {
                    ...c,
                    productName: e.productName,
                    productYlqxzcrbarmc: e.productYlqxzcrbarmc,
                    productCpbsbmtxmc: e.productCpbsbmtxmc,
                    productZxxsdycpbs: e.productZxxsdycpbs,
                    productZxxsydydsl: e.productZxxsydydsl,
                    productSpec: e.specName,
                  }
                }),
              })
            }
          }
        })
        let arr = []
        r.result.forEach((e, i) => {
          arr = arr.concat(
            e.positionInfoList.map((c) => {
              const o = { ...c }
              const row = self.goodList.filter((f) => f.specName == e.specName)
              if (row && row.length > 0) {
                o.productName = row[0].productName
                o.specName = e.specName
                o.productType = e.produtType
              }
              return o
            })
          )
          arr.push({
            warePid: '总计：',
            sums: e.sum,
            productType: e.produtType,
          })
          // if (i < r.result.length - 1) {
          //   arr.push({
          //     warePid: '总计：',
          //     sums: e.sum
          //   })
          // }
        })
        this.stockUpList = arr
      } catch (_) {}
    },
    async getInfo() {
      try {
        const self = this
        const params = { id: this.$route.query.id }
        const r = await outOrderInfo(params)
        this.info = r.result
        const { info } = this
        this.goodList = r.result.outOrderVtoSpecLists.map((e, i) => {
          e.outOrderDetailSpecLists = e.outOrderDetailSpecLists || []
          e.source = e.outOrderDetailSpecLists.map((c) => {
            return c
            // return {
            //   companyTo: info.companyTo,
            //   outOrderId: info.id,
            //   outOrderNo: info.orderNo,
            //   outOrderType: info.orderType,
            //   productCpbsbmtxmc: c.productCpbsbmtxmc,
            //   productName: c.productName,
            //   productSpec: c.productSpec,
            //   productYlqxzcrbarmc: c.productYlqxzcrbarmc,
            //   productZxxsdycpbs: c.productZxxsdycpbs,
            //   productZxxsydydsl: c.productZxxsydydsl,
            //   specId: c.specId,
            //   udi: c.udi,
            //   wareAid: c.wareAid,
            //   warePid: r.result.warePid,
            //   wareRid: r.result.wareRid,
            //   warehourse: r.result.warehourse,
            // }
          })
          if (e.source.length >= e.sum) {
            e.isChecked = true
          } else {
            e.isChecked = false
          }
          self.goodIndexObj[`${e.specName}-${e.productYlqxzcrbarmc}`] = i
          return e
        })
        await this.getStockUpList()
      } catch (_) {
        console.log('详情err', _)
      }
    },
    async onScan() {
      try {
        const { udi, goodIndexObj, info } = this
        const params = { udi }
        this.udi = undefined
        const r = await queryGoodByScanId(params)
        // 避免重复扫描
        if (this.scanObj[r.result.udi]) {
          return
        }
        const name = `${r.result.productSpec}-${r.result.companyTo}`
        if (goodIndexObj[name] !== undefined) {
          const o = this.goodList[goodIndexObj[name]]
          if (o.produtType * 1 == 1) {
            return
          }
          // 如果包裹已满 无法放入包裹中
          if (o.sum <= o.source.length) {
            this.errInfo = '已超出此规格出货数量'
            return
          }
          this.scanObj[r.result.udi] = 1
          o.source.unshift({
            companyTo: info.companyTo,
            outOrderId: info.id,
            outOrderNo: info.orderNo,
            outOrderType: info.orderType,
            productCpbsbmtxmc: r.result.productCpbsbmtxmc,
            productName: r.result.productName,
            productSpec: r.result.productSpec,
            productYlqxzcrbarmc: r.result.productYlqxzcrbarmc,
            productZxxsdycpbs: r.result.productZxxsdycpbs,
            productZxxsydydsl: r.result.productZxxsydydsl,
            specId: o.id,
            udi: r.result.udi,
            wareAid: r.result.wareAid,
            warePid: r.result.warePid,
            wareRid: r.result.wareRid,
            warehourse: r.result.warehourse,
          })
          this.errInfo = undefined
        } else {
          this.errInfo = '规格信息不匹配，无法录入'
        }
      } catch (_) {}
    },
    async check(e, i) {
      try {
        const { info, stockUpList } = this
        const params = {
          ...e,
          outOrderId: info.id,
          outOrderNo: info.orderNo,
          outOrderDetailSpecLists: e.source.map((c) => {
            return c
          }),
        }
        if (e.productType * 1 == 1) {
          params.positionInfos = stockUpList.filter((f) => f.specName == e.specName) || []
        }
        await scanBindGood(params)
        // this.$message.success('操作成功!')
        this.$set(this.goodList, i, { ...this.goodList[i], isChecked: true })
        // this.goodList = this.goodList
        // this.$forceUpdate()
      } catch (_) {}
    },
    async temporaryStorage() {
      try {
        const { info, goodList } = this
        const params = {
          id: info.id,
          orderNo: info.orderNo,
          outOrderVtoSpecLists: goodList.map((e) => {
            const o = {
              id: e.id,
            }
            return o
          }),
        }
        await outOrderTemporaryStorage(params)
        this.$message.success('提交成功!')
        this.$router.go(-1)
      } catch (_) {}
    },
    // 提交审核 审核通过 订单完结
    async submit() {
      try {
        const { info, goodList } = this
        const params = {
          id: info.id,
          orderNo: info.orderNo,
          outOrderVtoSpecLists: goodList.map((e) => {
            const o = {
              id: e.id,
            }
            return o
          }),
        }
        const API = {
          0: outOrderSubmitExamine,
          1: outOrderSubmitExamine,
          2: outOrderExaminePass,
          3: outOrderComplete,
        }
        await API[info.state](params)
        this.$message.success('提交成功!')
        this.$router.go(-1)
      } catch (_) {}
    },
  },
}
</script>

<style lang="scss" scoped>
.title-wrap {
  display: flex;
  .title {
    margin-right: 30px;
  }
}
.descriptions-title {
  font-size: 20px;
  font-weight: 650;
}
.good-header {
  display: flex;
  .scan-info {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}
.button-wrap {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
.err-info {
  font-size: 14px;
  color: red;
  margin-top: 20px;
}
</style>